package com.hades.xq.ares.titlebar

import android.content.Context
import android.support.v7.widget.Toolbar
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import kotlinx.android.synthetic.main.header_base.view.*
import kotlinx.android.synthetic.main.layout_toolbar_header.view.*

/**
 * Created by wellor on 2017/12/12.
 */
class CustomToolbar : Toolbar {

    private val bar by lazy {
        object : BaseTitleBar(this) {
            override fun setRight(imgId: Int, str: String?, l: OnClickListener?) {
                moreBtn.visibility = View.VISIBLE
                moreBtn.setOnClickListener(l)
                super.setRight(imgId, str, l)

            }
        }
    }

    private val backAlpha by lazy {
        backBtn.alpha
    }

    private val moreAlpha by lazy {
        moreBtn.alpha
    }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView(attrs)
    }


    private fun initView(attrs: AttributeSet?) {
        val attr = context.obtainStyledAttributes(attrs, R.styleable.CustomToolbar)
        val header = View.inflate(context, R.layout.layout_toolbar_header, null)


        header.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        addView(header)
        rl_head_rootview.visibility = View.GONE
        rl_head_rootview.alpha = 0f


        val secondaryBg = attr.getResourceId(R.styleable.CustomToolbar_secondaryBackground, 0)

        if (secondaryBg > 0) {
            setSecondaryBg(secondaryBg)
        }


        val leftIv = attr.getResourceId(R.styleable.CustomToolbar_secondaryLeftIv, R.drawable.ic_back_c)
        val rightIv = attr.getResourceId(R.styleable.CustomToolbar_secondaryRightIv, R.drawable.more_round_right)

        setSecondaryLeftIv(leftIv)
        setSecondaryRight(rightIv)

        attr.recycle()
        backBtn.setOnClickListener { bar.onBack() }
    }


    fun setUpAlpha(rate: Float) {

        backBtn.alpha = backAlpha.times(1 - rate)
        moreBtn.alpha = moreAlpha.times(1 - rate)
        rl_head_rootview.alpha = rate


        if (rate <= 0f) {
            rl_head_rootview.visibility = View.GONE
        } else {
            rl_head_rootview.visibility = View.VISIBLE
        }

//        Logger.d(rate)
    }

    fun setSecondaryBg(bg: Int) {
        secondaryBar.setBackgroundResource(bg)
    }


    fun setSecondaryLeftIv(imgId: Int) {
        backBtn.setImageResource(imgId)
    }

    fun setSecondaryRight(imgId: Int) {
        moreBtn.setImageResource(imgId)
    }


    fun getSecondaryRight(): ImageView? {
        return moreBtn
    }


    fun getTitleBar(): BaseTitleBar {
        return bar
    }

}